package com.ying.dogying.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ying.dogying.dao.ImUserDao;
import com.ying.dogying.entity.Const;
import com.ying.dogying.entity.ImUser;
import com.ying.dogying.entity.Response;
import com.ying.dogying.service.ImUserService;
import com.ying.dogying.shiro.AccountProfileDto;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 李华明
 * @since 2020-06-05
 */
@Service
public class ImUserServiceImpl extends ServiceImpl<ImUserDao, ImUser> implements ImUserService {
	private static Logger log = LoggerFactory.getLogger(ImUserServiceImpl.class);
    @Override
    public AccountProfileDto login(String username, String password) {
        log.info("ImUserServiceImpl---------------->进入用户登录判断，获取用户信息步骤");

        ImUser imUser = this.getOne(new QueryWrapper<ImUser>().eq("username", username));
        if(null == imUser) {
            throw new UnknownAccountException("账户不存在");
        }
        if(!imUser.getPassword().equals(password)) {
            throw new IncorrectCredentialsException("密码错误");
        }

        //更新最后登录时间
        imUser.setLastTime(new Date());
        this.updateById(imUser);

        AccountProfileDto profile = new AccountProfileDto();
        BeanUtil.copyProperties(imUser, profile);
        return profile;
    }

    @Override
    public Response register(ImUser imUser) {

        if(StringUtils.isBlank(imUser.getUsername()) || StringUtils.isBlank(imUser.getPassword())
                || StringUtils.isBlank(imUser.getEmail())) {
            return new Response().failure("必要字段不能为空");
        }
        ImUser user = this.getOne(new QueryWrapper<ImUser>().eq("email", imUser.getEmail()));
        if (null != user) {
            return new Response().failure("邮箱已经被注册了");
        }
        user = this.getOne(new QueryWrapper<ImUser>().eq("username", imUser.getUsername()));
        if (null != user) {
            return new Response().failure("昵称已经被注册了");
        }
        String password = SecureUtil.md5(imUser.getPassword());

        user = new ImUser();
        user.setUsername(imUser.getUsername());
        user.setPassword(password);
        user.setEmail(imUser.getEmail());
        user.setAvatar("/res/images/avatar/default.png");
        user.setPoint(0);
        user.setGender("0");
        user.setVipLevel(0);
        user.setPostCount(0);
        user.setCommentCount(0);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        this.save(user);
        return new Response().success("注册成功");
    }

    @Override
    public Response updateByParams(ImUser imUser, Long profileId, AccountProfileDto profile) {
        if (StringUtils.isBlank(imUser.getUsername())) {
            return new Response().failure("用户名不能为空");
        }
        ImUser user = this.getById(profileId);
        user.setUsername(imUser.getUsername());
        user.setGender(imUser.getGender());
        user.setSign(imUser.getSign());

        boolean b = this.updateById(user);
        if (b) {
            // 更新shiro信息
            profile.setUsername(imUser.getUsername());
            profile.setGender(imUser.getGender());
            profile.setSign(imUser.getSign());
        }
        return b ? new Response().success("更新成功") : new Response().failure("更新失败");
    }

    @Autowired
    Const aConst;
    @Override
    public Response upload(MultipartFile file, String type, Long profileId, AccountProfileDto profile) {
        if (file.isEmpty()) {
            return new Response().failure("上传失败");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);
        // 文件的上传路径
        String filepath = aConst.getUploadDir();
        if ("avatar".equalsIgnoreCase(type)) {
            fileName = "/avatar/avatar_" + profileId + suffixName;
        } else if ("post".equalsIgnoreCase(type)) {
            fileName = "/post/post_" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN) + suffixName;
        }
        File dest = new File(filepath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            log.info("上传成功后的文件路径为：" + filepath + fileName);

            String path = filepath + fileName;
            String url = aConst.getUploadUrl() + fileName;

            log.info("url---------------->{}", url);

            ImUser imUser = this.getById(profileId);
            imUser.setAvatar(url);
            this.updateById(imUser);
            // 更新shiro的信息
            profile.setAvatar(url);
            return new Response().success(url);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Response().success(null);
    }

}
